<script setup lang="ts">
import { computed, ref } from 'vue';

import { message } from 'ant-design-vue';

import CreditModal from './components/CreditModal.vue';
import ProductModal from './components/ProductModal.vue';
import RechargeModal from './components/RechargeModal.vue';
import SettlementModal from './components/SettlementModal.vue';

// 接口定义
interface Customer {
  id: string;
  name: string;
  petName: string;
  phone: string;
  memberLevel: 'gold' | 'normal';
  memberCard: string;
  balance: number;
  type: 'registered' | 'walkin';
}

interface Product {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  discountEligible: boolean;
  quantity: number;
  total: number;
  salesPerson: string;
  servicePerson: string;
}

// 响应式数据
const customerType = ref<'registered' | 'walkin'>('registered');
const searchKeyword = ref('');
const selectedCustomer = ref<Customer | null>(null);
const selectedProducts = ref<Product[]>([]);

// 模态框控制
const showProductModal = ref(false);
const showRechargeModal = ref(false);
const showCreditModal = ref(false);
const showSettlementModal = ref(false);

// 模拟顾客数据
const customers = ref<Customer[]>([
  {
    id: '1',
    name: '赵女士',
    petName: '球球',
    phone: '183****1234',
    memberLevel: 'gold',
    memberCard: '001',
    balance: 1000,
    type: 'registered',
  },
  {
    id: '2',
    name: '李先生',
    petName: '小白',
    phone: '139****5678',
    memberLevel: 'normal',
    memberCard: '002',
    balance: 500,
    type: 'registered',
  },
  {
    id: '3',
    name: '散客A',
    petName: '咪咪',
    phone: '138****9999',
    memberLevel: 'normal',
    memberCard: '',
    balance: 0,
    type: 'walkin',
  },
]);

// 表格列定义
const productColumns = [
  {
    title: '购买商品',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
  },
  {
    title: '参与打折',
    dataIndex: 'discountEligible',
    key: 'discountEligible',
    customRender: ({ text }: { text: boolean }) => (text ? '是' : '否'),
  },
  {
    title: '单价',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    customRender: ({ text }: { text: number }) => `¥${text}`,
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
  },
  {
    title: '合计',
    dataIndex: 'total',
    key: 'total',
  },
  {
    title: '销售人员',
    dataIndex: 'salesPerson',
    key: 'salesPerson',
  },
  {
    title: '服务人员',
    dataIndex: 'servicePerson',
    key: 'servicePerson',
  },
  {
    title: '操作',
    key: 'action',
  },
];

// 计算属性
const filteredCustomers = computed(() => {
  let filtered = customers.value.filter(
    (customer) => customer.type === customerType.value,
  );

  if (searchKeyword.value) {
    filtered = filtered.filter(
      (customer) =>
        customer.name.includes(searchKeyword.value) ||
        customer.petName.includes(searchKeyword.value) ||
        customer.phone.includes(searchKeyword.value),
    );
  }

  return filtered;
});

const totalAmount = computed(() => {
  return selectedProducts.value.reduce(
    (sum, product) => sum + product.total,
    0,
  );
});

// 方法
const handleCustomerTypeChange = () => {
  selectedCustomer.value = null;
  searchKeyword.value = '';
};

const handleCustomerSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const selectCustomer = (customer: Customer) => {
  selectedCustomer.value = customer;
  message.success(`已选择顾客: ${customer.name}`);
};

const openProductModal = () => {
  if (!selectedCustomer.value) {
    message.warning('请先选择顾客');
    return;
  }
  showProductModal.value = true;
};

const handleProductSelect = (products: Product[]) => {
  console.log('收到商品选择:', products);
  products.forEach((product) => {
    const existingProduct = selectedProducts.value.find(
      (p) => p.id === product.id,
    );
    if (existingProduct) {
      existingProduct.quantity += product.quantity;
      updateProductTotal(existingProduct);
      console.log('更新现有商品:', existingProduct);
    } else {
      const newProduct = {
        ...product,
        salesPerson: '曾前台',
        servicePerson: '曾前台',
        total: product.unitPrice * product.quantity,
      };
      selectedProducts.value.push(newProduct);
      console.log('添加新商品:', newProduct);
    }
  });
  console.log('当前选中商品列表:', selectedProducts.value);
  message.success(`已添加 ${products.length} 个商品`);
};

const updateProductTotal = (product: Product) => {
  product.total = product.unitPrice * product.quantity;
};

const removeProduct = (index: number) => {
  selectedProducts.value.splice(index, 1);
  message.success('商品已删除');
};

const openRechargeModal = () => {
  if (!selectedCustomer.value) {
    message.warning('请先选择顾客');
    return;
  }
  showRechargeModal.value = true;
};

const handleRechargeSuccess = (amount: number) => {
  if (selectedCustomer.value) {
    selectedCustomer.value.balance += amount;
    message.success(`充值成功，余额: ¥${selectedCustomer.value.balance}`);
  }
};

const openCreditModal = () => {
  if (!selectedCustomer.value) {
    message.warning('请先选择顾客');
    return;
  }
  if (selectedProducts.value.length === 0) {
    message.warning('请先添加商品');
    return;
  }
  showCreditModal.value = true;
};

const handleCreditSuccess = () => {
  message.success('挂账成功');
  resetSales();
};

const openSettlementModal = () => {
  if (!selectedCustomer.value) {
    message.warning('请先选择顾客');
    return;
  }
  if (selectedProducts.value.length === 0) {
    message.warning('请先添加商品');
    return;
  }
  showSettlementModal.value = true;
};

const handleSettlementSuccess = () => {
  message.success('结算成功');
  resetSales();
};

const resetSales = () => {
  selectedProducts.value = [];
  selectedCustomer.value = null;
  searchKeyword.value = '';
};
</script>

<template>
  <div class="sales-management">
    <!-- 左侧：顾客选择 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>顾客选择</h3>
      </div>

      <div class="customer-selection">
        <!-- 顾客类型选择 -->
        <div class="customer-type">
          <a-radio-group
            v-model:value="customerType"
            @change="handleCustomerTypeChange"
          >
            <a-radio value="registered">已登记顾客</a-radio>
            <a-radio value="walkin">散客</a-radio>
          </a-radio-group>
        </div>

        <!-- 顾客搜索 -->
        <div class="customer-search">
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索顾客"
            @search="handleCustomerSearch"
            style="width: 100%"
          >
            <template #enterButton>
              <a-button type="primary">选择顾客</a-button>
            </template>
          </a-input-search>
        </div>

        <!-- 顾客列表 -->
        <div class="customer-list">
          <div
            v-for="customer in filteredCustomers"
            :key="customer.id"
            class="customer-item"
            :class="{ active: selectedCustomer?.id === customer.id }"
            @click="selectCustomer(customer)"
          >
            <div class="customer-info">
              <div class="customer-name">{{ customer.name }}</div>
              <div class="customer-pet">{{ customer.petName }}</div>
              <div class="customer-phone">{{ customer.phone }}</div>
            </div>
            <div class="customer-status">
              <a-tag :color="customer.memberLevel === 'gold' ? 'gold' : 'blue'">
                {{ customer.memberLevel === 'gold' ? '金卡' : '普通' }}
              </a-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间：商品销售 -->
    <div class="center-panel">
      <div class="sales-content">
        <!-- 顾客信息显示 -->
        <div v-if="selectedCustomer" class="customer-display">
          <div class="customer-details">
            <div class="detail-item">
              <span class="label">顾客姓名:</span>
              <span class="value">{{ selectedCustomer.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">宠物名:</span>
              <span class="value">{{ selectedCustomer.petName }}</span>
            </div>
            <div class="detail-item">
              <span class="label">联系方式:</span>
              <span class="value">{{ selectedCustomer.phone }}</span>
            </div>
            <div class="detail-item">
              <span class="label">会员卡:</span>
              <a-select
                v-model:value="selectedCustomer.memberCard"
                style="width: 120px"
                size="small"
              >
                <a-select-option value="001">001</a-select-option>
                <a-select-option value="002">002</a-select-option>
              </a-select>
            </div>
            <div class="detail-item">
              <span class="label">余额:</span>
              <span class="value balance">¥{{ selectedCustomer.balance }}</span>
              <a-button type="link" size="small" @click="openRechargeModal">
                充值
              </a-button>
            </div>
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="product-section">
          <div class="section-header">
            <h3>购买商品</h3>
            <a-button type="primary" @click="openProductModal">
              + 商品
            </a-button>
          </div>

          <div class="product-table">
            <a-table
              :columns="productColumns"
              :data-source="selectedProducts"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'quantity'">
                  <a-input-number
                    v-model:value="record.quantity"
                    :min="1"
                    size="small"
                    style="width: 80px"
                    @change="updateProductTotal(record)"
                  />
                </template>
                <template v-else-if="column.key === 'total'">
                  <span class="total-amount"
                    >¥{{ record.total.toFixed(2) }}</span
                  >
                </template>
                <template v-else-if="column.key === 'salesPerson'">
                  <a-select
                    v-model:value="record.salesPerson"
                    style="width: 100px"
                    size="small"
                  >
                    <a-select-option value="曾前台">曾前台</a-select-option>
                    <a-select-option value="李销售">李销售</a-select-option>
                    <a-select-option value="王销售">王销售</a-select-option>
                  </a-select>
                </template>
                <template v-else-if="column.key === 'servicePerson'">
                  <a-select
                    v-model:value="record.servicePerson"
                    style="width: 100px"
                    size="small"
                  >
                    <a-select-option value="曾前台">曾前台</a-select-option>
                    <a-select-option value="张服务">张服务</a-select-option>
                    <a-select-option value="刘服务">刘服务</a-select-option>
                  </a-select>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    danger
                    size="small"
                    @click="removeProduct(index)"
                  >
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </div>
        </div>

        <!-- 结算区域 -->
        <div class="settlement-section">
          <div class="total-info">
            <span class="total-label">合计:</span>
            <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="action-buttons">
            <a-button type="default" @click="openCreditModal"> 挂账 </a-button>
            <a-button type="primary" @click="openSettlementModal">
              立即结算
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品选择模态框 -->
    <ProductModal
      :visible="showProductModal"
      @update:visible="showProductModal = $event"
      @select="handleProductSelect"
    />

    <!-- 充值模态框 -->
    <RechargeModal
      :visible="showRechargeModal"
      :customer="selectedCustomer"
      @update:visible="showRechargeModal = $event"
      @success="handleRechargeSuccess"
    />

    <!-- 挂账模态框 -->
    <CreditModal
      :visible="showCreditModal"
      :amount="totalAmount"
      :customer="selectedCustomer"
      @update:visible="showCreditModal = $event"
      @success="handleCreditSuccess"
    />

    <!-- 结算模态框 -->
    <SettlementModal
      :visible="showSettlementModal"
      :amount="totalAmount"
      :customer="selectedCustomer"
      :products="selectedProducts"
      @update:visible="showSettlementModal = $event"
      @success="handleSettlementSuccess"
    />
  </div>
</template>

<style scoped>
.sales-management {
  display: flex;
  height: 100%;
  background: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 320px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.customer-selection {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.customer-type {
  margin-bottom: 16px;
}

.customer-search {
  margin-bottom: 16px;
}

.customer-list {
  flex: 1;
  overflow-y: auto;
}

.customer-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.customer-item:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.customer-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.customer-info {
  margin-bottom: 8px;
}

.customer-name {
  margin-bottom: 4px;
  font-weight: bold;
  color: #333;
}

.customer-pet {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.customer-phone {
  font-size: 12px;
  color: #999;
}

.center-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: white;
}

.sales-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 24px;
}

.customer-display {
  padding: 16px;
  margin-bottom: 24px;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.customer-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.detail-item .label {
  min-width: 80px;
  font-size: 14px;
  color: #666;
}

.detail-item .value {
  font-weight: bold;
  color: #333;
}

.detail-item .balance {
  color: #ff4d4f;
}

.product-section {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.product-table {
  flex: 1;
  overflow: hidden;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.total-amount {
  font-weight: bold;
  color: #ff4d4f;
}

.settlement-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.total-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.total-label {
  font-size: 16px;
  color: #333;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 12px;
}
</style>
